<?php
namespace app\admin\controller;
use think\Db;
/**
 * #接任务管理 微手接任务管理控制器
 */
class Taskallocation extends Common{
    /**
     * #微手任务列表
     * @return view
     */
    function index($keyword='',$range=''){
        if(is_string($range)){
            $range=explode(',', $range);
        }
        
        $params=[
            'range'=>$range,
            'keyword'=>$keyword,
        ];
        $options=[
            'order'=>'id desc',
            'field'=>'id,uname,title,type,tag,status,limit,reward,illustrate,overtime,number,aquantity,squantity,fquantity,starttime,endtime,createtime',
        ];
        $map=[];
        if(!empty($keyword)){
            $map['uname']=['uname','like',"%{$keyword}%"];
        }
        if(!empty($range)){
            if(count($range)===2){
                $map['createtime']=['createtime','between',[$range[0]/1000,$range[1]/1000+86400]];
            }else{
                $map['createtime']=['createtime','>=',$range[0]/1000];
            }
        }
        $list=model('release_task')->readAll($map,true,$options)->appends($params);
        $this->assign('list',$list);
        $this->assign('params',json_encode($params));
        return view();
    }
    
    /**
     * 上架、下架
     * @param  integer $id ID
     * @return [type]      [description]
     */
    function close($id=0){
        if(request()->isAjax()||request()->isPost()){
            $this->superCheck();
            $ids=input('ids/a',[]); // 多项
            if($id<=0&&empty($ids)){
                $this->error(lang('Data does not exist'));
            }
            $where="";
            if(!empty($ids)){
                $ids=implode(',', $ids);
                $where=" `id` in ({$ids}) ";
            }else{
                $where=" `id`={$id} ";
            }
            $rs=model('ReleaseTask')->close($where,'status',true);
            if($rs){
                $this->success(lang('Successful operation'));
                die;
            }
            $this->error(lang('Failed operation'));
        }
    }
    function add($id=0){
        $task=[];
        $step=[];
        if($id>0){
            $field='id,title,type,tag,status,limit,reward,illustrate,step,overtime,number,starttime,endtime';
            $task=model('ReleaseTask')->read(['id'=>$id],$field);
            if(!empty($task)){
                $task['tag']=explode(',', $task['tag']);
                $task['range']=[$task['starttime']*1000,$task['endtime']*1000];
                if(!empty($task['step'])){
                    $step=json_decode($task['step'],true);
                }
                foreach($step as $k => $v) {
                    $filelist=[];
                    if(!empty($v['image_group'])){
                        $imagePrefix=images();
                        foreach($v['image_group'] as $c) {
                            $filelist[]=[
                                'href'=>$c,
                                'url'=>$imagePrefix.$c
                            ];
                        }
                    }
                    $step[$k]['filelist']=$filelist;
                }
                unset($task['starttime'],$task['endtime'],$task['step']);
            }
        }
        $this->assign('task',json_encode($task));
        $this->assign('task_step',json_encode($step));
        return view();
    }
    function addHandle(){
        if(request()->isAjax()||request()->isPost()){
            $id=input('id/d',0);
            $range=input('range/a',[]);
            $steps=input('steps/a',[]);
            $data=[
                'title'=>input('title/s',''),
                'tag'=>implode(',',input('tag/a',[])),
                'type'=>input('type/d'),
                'status'=>input('status/d',1),
                'overtime'=>input('overtime/d'),
                'reward'=>input('reward/d'),
                'number'=>input('number/d'),
                'limit'=>input('limit/d'),
                'illustrate'=>input('illustrate/s',''),
            ];
            if(count($range)===2){
                $data['starttime']=$range[0]/1000;
                $data['endtime']=$range[1]/1000;
            }
            
            if($id>0){
                $has=model('ReleaseTask')->where(['id'=>$id])->count();
                if(!$has){
                    $id=0;
                }else{
                    foreach ($data as $k => $v) {
                        if(empty($v)){
                            unset($data[$k]);
                        }
                    }
                }
            }
            if(isset($data['title'])&&empty($data['title'])){
                $this->error('任务标题不能为空');
            }
            if(isset($data['tag'])&&empty($data['tag'])){
                $this->error('请至少选择一项任务标签');
            }
            if(isset($data['reward'])&&$data['reward']<0){
                $this->error('任务奖励为必填项且不能小于 0');
            }
            if(isset($data['number'])&&$data['number']<0){
                $this->error('任务总数为必填项且不能小于 0');
            }
            if(isset($data['limit'])&&$data['limit']<0){
                $this->error('用户可领次数为必填项且不能小于 0');
            }
            if(isset($data['starttime'])&&empty($data['starttime'])){
                $this->error('请设置任务时间范围');
            }
            if(isset($data['endtime'])&&empty($data['endtime'])){
                $this->error('请设置任务时间范围');
            }

            foreach ($steps as $k => $v) {
                if(isset($v['filelist'])){
                    unset($v['filelist']);
                    $steps[$k]=$v;
                }
            }
            $data['step']=json_encode($steps);
            $data['image_group']=json_encode($this->getImageGroup($steps));
            if($id>0){
                $data['id']=$id;
                model('ReleaseTask')->edit($data);
                $this->success('编辑成功',url('index'));die;
            }else{
                $data['createtime']=time();
                $user=$this->user;
                $data['uid']=$user['id'];
                $data['uname']=$user['name'];
                $add=model('ReleaseTask')->add($data);
                if(isset($add['id'])){
                    $this->success('创建成功',url('index'));die;
                }
                $this->error('系统繁忙,创建失败');
            }
                    
        }
    }
    /**
     * 上传图片
     * @return [type] [description]
     */
    function loadStepPic(){
        $file=request()->file('file');
        if($file){
            $res=$this->loadHeadImg($file);
            if($res['success']){
                $index=input('index/s','-1');
                $res['index']=$index;
                $id=input('id/d',0);
                if($id>0){
                    $has=model('ReleaseTask')->read(['id'=>$id],'step,image_group')->toArray();
                    if(isset($has['step'])){
                        $step=json_decode($has['step'],true);
                        if(empty($step)){
                            $step=[];
                        }
                        if(isset($step[$index])){
                            if(isset($step[$index]['image_group'])){
                                $step[$index]['image_group'][]=$res['msg'];
                            }else{
                                $step[$index]['image_group']=[$res['msg']];
                            }
                        }else{
                            $step[]=[
                                'type'=>input('type/d'),
                                'text'=>input('text/s',''),
                                'link'=>input('link/s',''),
                                'image_group'=>[$res['msg']],
                            ];
                        }
                        $image_group=$this->getImageGroup($step);
                        $image_group=json_encode($image_group);
                        $step=json_encode($step);
                        model('ReleaseTask')->edit([
                            'id'=>$id,
                            'step'=>$step,
                            'image_group'=>$image_group,
                        ]);
                    }
                }
                return json($res['msg'],0,$res);
            }
            return json($res['msg'],1);
        }
    }
    function delStepPic($href=null){
        if(request()->isAjax()||request()->isPost()){
            if(is_null($href)){
                $this->error('该图片不存在,或可能已经删除');
            }
            $id=input('id/d',0);

            if(is_array($href)){
                foreach ($href as $v) {
                    $this->deleteUploadFile($v);
                }
            }else{
                $this->deleteUploadFile($href);
            }
            $change=false;
            $step=[];
            if($id>0){
                $has=model('ReleaseTask')->read(['id'=>$id],'step')->toArray();
                if(isset($has['step'])&&!empty($has['step'])){
                    $step=json_decode($has['step'],true);
                    if(empty($step)){
                        $step=[];
                    }
                }
                foreach ($step as $key => $v) {
                    if(!isset($v['image_group']))continue;
                    if(is_array($href)){
                        foreach ($href as $h) {
                            if(false!==$k=array_search($h, $v['image_group'])){
                                unset($step[$key]['image_group'][$k]);
                                $change=true;
                            }
                        }
                    }else{
                        if(false!==$k=array_search($href, $v['image_group'])){
                            if($k===0){
                                unset($step[$key]['image_group']);
                            }else{
                                unset($step[$key]['image_group'][$k]);
                            }
                            $change=true;
                        }
                    }
                    if(isset($step[$key])){
                        $filelist=[];
                        if(isset($v['image_group'])&&!empty($v['image_group'])){
                            $imagePrefix=images();
                            foreach($v['image_group'] as $c) {
                                $filelist[]=[
                                    'href'=>$c,
                                    'url'=>$imagePrefix.$c
                                ];
                            }
                        }
                        $step[$key]['filelist']=$filelist;
                    }
                }
                if($change){
                    $b=$step;
                    unset($b['filelist']);
                    $image_group=$this->getImageGroup($b);
                    model('ReleaseTask')->edit([
                        'id'=>$id,
                        'step'=>json_encode($b),
                        'image_group'=>json_encode($image_group),
                    ]);
                    $this->success('','',$step);die;
                }
            }
            
            $this->success('');
        }
    }
    function delTask($id=0){
        if(request()->isAjax()||request()->isPost()){
            if($id<=0){
                $this->error('该条记录不存在或可能已经删除');
            }
            $task=model('ReleaseTask')->read(['id'=>$id],'step');
            if(empty($task)){
                $this->error('该条记录不存在或可能已经删除');
            }
            $del=model('ReleaseTask')->del(['id'=>$id]);
            // 移除图片
            if($del&&!empty($task['step'])){
                $step=json_decode($task['step'],true);
                foreach ($step as $v) {
                    if(isset($v['image_group'])){
                        foreach ($v['image_group'] as $href) {
                            $this->deleteUploadFile($href);
                        }
                    }
                }
            }
            $this->success('删除成功');
        }
    }
    function examine($status='2',$keyword='',$range='',$state=0){
        if(is_string($range)){
            $range=explode(',', $range);
        }
        $map=[];
        $params=[
            'state'=>$state,
            'range'=>$range,
            'status'=>$status,
            'keyword'=>$keyword,
        ];
        if($status!=0){
            $map['status']=$status;
        }
        if($state>0){
            $params['status']='0';
            $map['status']=['status','in',[-1,3]];
        }
        if(!empty($keyword)){
            $map['uname|title']=['uname|title','like',"%{$keyword}%"];
        }
        if(!empty($range)){
            if(count($range)===2){
                $map['submittime']=['submittime','between',[$range[0]/1000,$range[1]/1000+86400]];
            }else{
                $map['submittime']=['submittime','>=',$range[0]/1000];
            }
        }
        $options=[
            'order'=>'id desc',
        ];
        $list=model('member_task')->readAll($map,true,$options)->appends($params);
        foreach ($list as $k => $v) {
            if(empty($v['submission'])){
                $list[$k]['submission']=[];
            }else{
                $list[$k]['submission']=json_decode($v['submission'],true);
            }
        }
        
        $this->assign('list',$list);
        $this->assign('params',json_encode($params));
        return view();
    }
    // 审核处理
    function handle($id=0,$reason='',$status=0){
        if(request()->isAjax()||request()->isPost()){
            if($id<=0){
                $this->error('该项数据不存在');
            }
            $has=model('member_task')->read(['id'=>$id],'uid,tid,status,type,reward');
            if(empty($has)){
                $this->error('该项数据可能已经删除');
            }
            if($has['status']==3||$has['status']==-1){
                $this->error('该条记录已经审核过,请勿重复操作');
            }
            if($has['status']!=2){
                $this->error('该条记录未提交或已过期，暂不可审核');
            }
            if(empty($reason)){
                $this->error('请填写备注说明');
            }
            if($status==3){ //通过
                $result=true;
                Db::startTrans();
                try {
                    $e=model('member_task')->edit([
                        'id'=>$id,
                        'examinetime'=>time(),
                        'status'=>3,
                        'reason'=>$reason,
                    ]);
                    if(!$e){
                        exception('审核失败，请稍后再试');
                    }
                    $user=model('member')->read(['id'=>$has['uid']],'tel');
                    $tel=preg_replace('/^(\d{3})\d+(\d{4})$/',"\$1****\$2", $user['tel']);
                    $field='money';
                    $newsMsg="恭喜{$tel}获得任务奖励{$has['reward']}元";
                    if($has['type']==2){
                        $field='coin';
                        $newsMsg="恭喜{$tel}获得任务奖励{$has['reward']}".lang('coin');
                    }
                    $inc=model('member')->where(['id'=>$has['uid']])->setInc($field,$has['reward']);
                    if(!$inc){
                        exception('系统繁忙，奖励入账失败!');
                    }
                    // 任务通过数量累计
                    $hasTask=model('release_task')->where(['id'=>$has['tid']])->count();
                    if($hasTask){
                        $tinc=model('release_task')->where(['id'=>$has['tid']])->setInc('fquantity');
                        if(!$tinc){
                            exception('系统繁忙，任务记录失败!');
                        }
                    }
                    $res=model('news')->add([
                        'uid'=>$has['uid'],
                        'content'=>$newsMsg,
                        's_time'=>time(),
                    ]);
                    if(empty($res)){
                        exception('系统繁忙,记录写入失败');
                    }
                    $module=model('artmodule')->read(['name'=>'single'],'id');
                    $f=model('finance')->log($has['uid'],$has['uid'],$has['reward'],5,[
                        'remark'=>'任务奖励',
                        'memo'=>'task_bonus_'.$field,
                        'module_id'=>$module['id'],
                    ]);
                    if(empty($f)){
                        exception('系统繁忙,奖金记录写入失败');
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $result=$e->getMessage();
                }
                if(true!==$result){
                    $this->error($result);
                }else{
                    $this->success('审核成功');
                    die;
                }
            }elseif($status==-1){ //拒绝 
                $e=model('member_task')->edit([
                    'id'=>$id,
                    'examinetime'=>time(),
                    'status'=>-1,
                    'reason'=>$reason,
                ]);
                if(!$e){
                    $this->error('审核失败，请稍后再试');
                }
                $this->success('审核成功');die;
                
            }else{
                $this->error('暂不支持的操作类型!');
            }
        }
    }
    private function getImageGroup($step){
        $arr=[];
        if(!empty($step)&&is_array($step)){
            foreach ($step as $v) {
                if(isset($v['image_group'])){
                    $arr=array_merge($arr,$v['image_group']);
                }
            }
        }
        return $arr;
    }

}